package ticTacToe;

import java.util.Scanner;

public class TicTacToeGame {

	private Player player1;
	private Player player2;
	private Board board;
	private Referee referee;

	public TicTacToeGame(Player player1, Player player2) {
		System.out.println("TicTacToeGame.TicTacToeGame()");

		this.player1 = player1;
		this.player2 = player2;
		board = new Board();
		referee = new Referee(board);

		testGame();
	}

	public void testGame() {
		player1.setMyTurn(true);
		player2.setMyTurn(false);
		board.displayBoard();
		Position position = null;

		Scanner in;

		while (!referee.isWin() & !referee.isDraw()) {

			if (player1.isMyTurn()) {
				System.out.println("Player 1 ... plz play");

				in = new Scanner(System.in);

				int x = in.nextInt();
				int y = in.nextInt();

				position = new Position(x, y);

				if ((position.getCoords()[0] < 3)
						& (position.getCoords()[1] < 3)) {

					if (board.isSlotFree(position)) {
						XPiece xPiece = new XPiece(position);
						board.addPiece(xPiece);
						player1.setMyTurn(false);
						player2.setMyTurn(true);
					} else {
						System.out
								.println("THIS slot is not Free... Try Again");
					}
				} else {
					System.out.println("wrong position... Try Again");
				}

				if (referee.isWin()) {
					System.out
							.println("=============Player1 Wins=============");
				} else if (referee.isDraw()) {
					System.out.println("DRAAAAAAAAAAAAAAAAWWWWWW");

				}

			} else if (player2.isMyTurn()) {
				System.out.println("Player 2 ... plz play");
				in = new Scanner(System.in);
				int x = in.nextInt();
				int y = in.nextInt();

				position = new Position(x, y);
				if ((position.getCoords()[0] < 3)
						& (position.getCoords()[1] < 3)) {

					if (board.isSlotFree(position)) {
						OPiece oPiece = new OPiece(position);
						board.addPiece(oPiece);
						player1.setMyTurn(true);
						player2.setMyTurn(false);
					} else {
						System.out
								.println("THIS slot is not Free... Try Again");
					}

				} else {
					System.out.println("wrong position... Try Again");
				}
				if (referee.isWin()) {
					System.out
							.println("=============Player2 Wins=============");
				} else if (referee.isDraw()) {
					System.out.println("DRAAAAAAAAAAAAAAAAWWWWWW");

				}

			} else {
				System.out.println("ERRRRRRRRRRRRRRRRRRRRRRRRRRRROR");
			}
			board.displayBoard();
		}

	}

}
